var app = getApp()
var d = new Date()
var y = d.getFullYear()
var m = d.getMonth() + 1
m < 10 ? m = '0' + m : m
var d1 = d.getDate()
d1 < 10 ? d1 = '0' + d1 : d1
var today = `${y}-${m}-${d1}`
Page({
  data: {
    noData: false,
    pickerDay: {},
    today,
    date: '', // 日期
    activeIndex: 1, //当前tab
    lists: [],
    topThree: [], // 排序：亚军，冠军，季军
    form: {
      userId: 446,
      form: '3',
      dateTime: '',
      tV2CustomMatchScheduleId: '',
      pageNum: "1",
      pageSize: "10"
    },

    maxKcal: 0, // 排行榜最大卡路里
  },
  onLoad(options) {
    if (!options.id) {
      wx.showToast({
        icon: 'none',
        title: '打卡赛id不能为空',
        duration: 5000
      })
      setTimeout(() => {
        wx.navigateBack({})
      }, 5000)
      return
    }
    
    // 处理参数
    var user = wx.getStorageSync('user')
    var form = this.data.form
    form.userId = options.userId
    form.tV2CustomMatchScheduleId = options.id
    form.dateTime = options.dateTime || ''

    form.dateTime && this.setDate(form.dateTime)

    // 处理start ， end日期
    var start = options.start.split(' ')[0]
    var end = options.end.split(' ')[0]
    var d = new Date((new Date(end)).getTime() - 24 * 60 * 60 * 1000)
    var y = d.getFullYear()
    var m = d.getMonth() + 1
    var day = d.getDate()
    m = m < 10? '0' + m : m
    day = day < 10 ? '0' + day : day
    end = `${y}-${m}-${day}`

    // 判断最后一天是否过了
    if ((new Date(end)).getTime() - (new Date(this.data.today)).getTime() > 0) {
      end = this.data.today
    }

    var pickerDay = this.data.pickerDay
    pickerDay.start = start
    pickerDay.end = end
    this.setData({
      pickerDay
    })
    this.getRanking()
  },

  getRanking() {
    var _this = this
    _this.data.form.dateTime = this.data.date
    app.middleware.requestAjax({
      serAddr: app.serAddrs.getAwardRanking,
      data: _this.data.form,
      cancelToast: true,
      success: function (res) {
        var data = _this.handleList(res.data)
        data.noData = false
        _this.setData(data)
      },
      fail: function (res) {
        _this.setData({ noData: true })
        app.middleware.showToast(res && res.msg || "加载失败");
      }
    })
  },

  updateForm(){

  },

  tapNav(e) {
    var activeIndex
    if (e.target.dataset.index == 1) {
      activeIndex = 1
    } else {
      activeIndex = 0
    }
    this.setData({
      activeIndex,
      date: ''
    })
    this.getRanking()
  },

  setDate(date = '') {
    if (!date) {
      var d = new Date()
      var y = d.getFullYear()
      var m = d.getMonth()
      if (m < 10) {
        m = '0' + m
      }
      var d1 = d.getDate()
      if (d1 < 10) {
        d1 = '0' + d1
      }
      var date = [y, m, d1].join('-')
    }
    this.setData({
      date,
      activeIndex: 0
    })
    this.getRanking()
  },
  // 修改日期
  changeDate(e) {
    this.setDate(e.detail.value)
  },
  /**
   * 处理成我已经写好的格式
   * [{
   *    avator: './images/test.png',
   *    name: '傻逼',
   *    money: '￥19.00',
   *    index: '4'
   * }]
   */
  handleList(lists) {
    console.error(lists)
    var maxKcal = this.data.maxKcal
    var danwei = ''
    if (lists.length > 0) {
      danwei = lists[0].matchWay ==  'step' ? ' 步' : ' kcal'
    }

    lists.forEach(item => {
      // 获取最大的kcal，进行画横条
      if (item.sumData > maxKcal) {
        maxKcal = item.sumData
      }

      this.setData({
        maxKcal
      })
    })

    lists = lists.map((item, index) => {

      var percent = (item.sumData / maxKcal).toFixed(2) * 100 + '%'
      var kcal = 0

      // 判断单位
      if (item.matchWay=='kcal') {
        kcal = Number(item.sumData).toFixed(2)
      } else {
        kcal = Number(item.sumData).toFixed(0)
      }
      return {
        avator: item.headPortrait,
        name: item.username,
        kcal: danwei != 'kcal' ? kcal + danwei : kcal + danwei,
        percent,
        index: index + 1
      }
    })

    var i = 0
    var topThree = []
    var item = {
      avator: ' ',
      name: '无',
      kcal: '0.00' + danwei,
      percent: ' ',
      index: 2
    }
    var guanjun = null
    var yajun = null
    var jijun = null
    var i = 0

    var tempArr = []
    while(i<3){
      if (lists[0]) {
        tempArr.push(lists.shift())
      }
      i++
    }

    topThree = [tempArr[1]?tempArr[1]:item, tempArr[0]?tempArr[0]:item, tempArr[2]?tempArr[2]:item]

    return {
      topThree,
      lists
    }
  }
})